using System.IO;
using UnityEngine;

namespace ZyGame.Sound
{
    class SoundManager : Singleton<SoundManager>
    {
        private UnityEngine.AudioSource sound;
        private UnityEngine.AudioSource effect;

        public SoundManager()
        {
            sound = new GameObject("SoundPlayer").AddComponent<AudioSource>();
            effect = new GameObject("EffectSoundPlayer").AddComponent<AudioSource>();
            GameObject.DontDestroyOnLoad(sound.gameObject);
            GameObject.DontDestroyOnLoad(effect.gameObject);
        }

        public void PlaySound(string name, bool isLoop)
        {
            if (isLoop is false)
            {
                sound.PlayOneShot(Client.Resource.LoadAsset<AudioClip>(name));
                return;
            }

            sound.loop = isLoop;
            sound.clip = Client.Resource.LoadAsset<AudioClip>(name);
            sound.Play();
        }


        public void PlayEffectSound(string name, bool isLoop)
        {
            if (isLoop is false)
            {
                effect.PlayOneShot(Client.Resource.LoadAsset<AudioClip>(name));
                return;
            }

            effect.loop = isLoop;
            effect.clip = Client.Resource.LoadAsset<AudioClip>(name);
            effect.Play();
        }


        public float GetSoundVolument()
        {
            return sound.volume;
        }

        public float GetEffectSoundVolument()
        {
            return effect.volume;
        }

        public void SetSoundVolument(float volument)
        {
            sound.volume = volument;
        }

        public void SetEffectSoundVolument(float volument)
        {
            effect.volume = volument;
        }

        public void StopPlay(string name)
        {
            if (sound.clip.name == Path.GetFileNameWithoutExtension(name))
            {
                sound.Stop();
            }

            if (effect.clip.name == Path.GetFileNameWithoutExtension(name))
            {
                effect.Stop();
            }
        }

        public void ResumeSound()
        {
            if (sound is null || sound.clip is null)
            {
                return;
            }

            if (sound.isPlaying)
            {
                return;
            }

            sound.Play();
        }

        public void ResumeEffectSound()
        {
            if (effect is null || effect.clip is null)
            {
                return;
            }

            if (effect.isPlaying)
            {
                return;
            }

            effect.Play();
        }

        public void ResumeAll()
        {
            ResumeSound();
            ResumeEffectSound();
        }

        public void StopAllPlay()
        {
            sound.Stop();
            effect.Stop();
        }
    }
}